package aliyunSms

import (
	"errors"
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v3/client"
	utils "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

//accessKeyId = LTAI5tLfDWo2dJ9wQCPNXJZA
//accessKeySecret = rk3rqjCwsMSkrOqSGOIs93HvubcZmG
//"黑龙江穿山甲网络", "SMS_227665232"

var accessKeyId = "LTAI5tLfDWo2dJ9wQCPNXJZA"
var accessKeySecret = "rk3rqjCwsMSkrOqSGOIs93HvubcZmG"

// Send
// 发送验证码
// @param code	验证码
// @param phone	手机号
// @param signName	标题
// @param templateCode	模板id
func Send(code, phone, signName, templateCode string) error {
	client, err := CreateClient(tea.String(accessKeyId), tea.String(accessKeySecret))
	if err != nil {
		return err
	}

	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		PhoneNumbers:  tea.String(phone),
		SignName:      tea.String(signName),
		TemplateCode:  tea.String(templateCode),
		TemplateParam: tea.String("{\"code\":\"" + code + "\"}"),
	}

	runtime := &utils.RuntimeOptions{}
	// 复制代码运行请自行打印 API 的返回值
	rest, err := client.SendSmsWithOptions(sendSmsRequest, runtime)
	if err != nil {
		return err
	}

	fmt.Println(rest.Body)
	if *rest.Body.Code == "OK" {
		return nil
	} else {
		return errors.New(*rest.Body.Message)
	}

}

// CreateClient
// 使用AK&SK初始化账号Client
// @param accessKeyId
// @param accessKeySecret
// @return Client
// @throws Exception
func CreateClient(accessKeyId *string, accessKeySecret *string) (_result *dysmsapi20170525.Client, _err error) {
	config := &openapi.Config{
		// 您的 AccessKey ID
		AccessKeyId: accessKeyId,
		// 您的 AccessKey Secret
		AccessKeySecret: accessKeySecret,
	}
	// 访问的域名
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	_result = &dysmsapi20170525.Client{}
	_result, _err = dysmsapi20170525.NewClient(config)
	return _result, _err
}
